import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import SelfCard from "@/components/SelfCard.vue";
import LoginView from "@/views/LoginView.vue";
import { useAuthStore } from '@/stores/auth';
import SurveyTable from "@/components/SurveyTable.vue";
import SurveyDetail from "@/components/SurveyDetail.vue";
import WriteSurey from "@/components/WriteSurey.vue";
import SurveyRecord from "@/components/SurveyRecord.vue";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
      redirect:'/index',
      children:[
        {
          path: 'index',
          name: 'index',
          component: SurveyTable,
        },
        {
          path: 'self',
          name: 'self',
          component: SelfCard,
        },
        {
          path: '/survey/:surveyId',
          name: 'SurveyDetail',
          component: SurveyDetail,
          props: true // 允许路由传参
        },
        {
          path: '/write/:surveyId',
          name: 'WriteSurey',
          component: WriteSurey,
          props: true // 允许路由传参
        },
        {
          path: '/record-survey',
          name: 'SurveyRecord',
          component: SurveyRecord,
        },
      ]
    },
    {
      path: '/login',
      name: 'login',
      component: LoginView,
    }
  ],
})

// 设置路由守卫
router.beforeEach((to, from, next) => {
  const authStore = useAuthStore();
  const token = authStore.token || localStorage.getItem('token'); // 从 Pinia 或 localStorage 获取 token

  // 判断访问的路由是否需要授权
  if (to.name !== 'login' && !token) {
    // 如果需要登录但没有 token，跳转到登录页
    next({ name: 'login' });
  } else {
    // 如果已登录或访问的是登录页面，允许访问
    next();
  }
});

export default router
